// 公共路由中间件
const { validationResult, param } = require('express-validator')
const expressJwt = require('express-jwt')
const { jwtSecret } = require('../config/config.default')
const { STATUS } = require('../utils/constants')

// 统一提取收集验证失败信息
const errorHandler = (err, req, res, next) => {
  const message = []

  if (err instanceof Error) {
    if (['UnauthorizedError', 'credentials_required'].includes(err.name)) {
      // token 验证失败
      res.status(200).json({
        status: STATUS.UNAUTHORIZED,
        msg: '请登录'
      })
      return
    }

    message.push(err.message)
  } else if (typeof err === 'string') {
    // 自定义错误提示
    message.push(err)
  } else if (Array.isArray(err)) {
    // express-validator 错误信息
    err.forEach(error => {
      if (error.msg) {
        message.push(error.msg)
      }
    })
  }

  res.status(200).json({
    status: STATUS.FAILED,
    msg: message.join('; ')
  })
}

// 判断校验是否成功
const validResultCallback = (req, res, next) => {
  const result = validationResult(req)
  if (!result.isEmpty()) {
    next(result.array())
    return
  }
  next()
}

// 解析 token 并存储到 req.auth
// header => Authorization: Bearer <JSON WEB TOKEN>
const tokenParser = expressJwt({
  secret: jwtSecret,
  algorithms: ['HS256'], // token 算法，jsonwebtoken 默认 HS256
  requestProperty: 'auth' // 将 payload 存储到 req.auth
})

// params 上的 id 校验
const idValidator = [
  param('id').exists({ checkFalsy: true }).custom(value => /^\d+$/.test(value))
]

// 超管身份验证
const isAdmin = (req, res, next) => {
  if (req.auth.id !== 1) {
    res.status(200).json({
      status: STATUS.UNAUTHORIZED,
      msg: '你不是超级管理员，无权操作'
    })
    return
  }
  next()
}

module.exports = {
  errorHandler,
  validResultCallback,
  tokenParser,
  idValidator,
  isAdmin
}
